import axios from 'axios'
import { push } from 'notivue'
import httpErrorHandler from './httpErrorHandler'

// 请求头
export const contentType = [
	'application/json; charset=UTF-8',
	'application/x-www-form-urlencoded; charset=UTF-8',
	'multipart/form-data; charset=UTF-8',
]

const requestBaseURL = '/api'
// 创建 axios 请求实例
const Axios = axios.create({
	baseURL: requestBaseURL,
	timeout: 3000, // 请求 2s 超时
	withCredentials: false, // 跨域请求是否需要携带 cookie
})

// 全局 http request 拦截
Axios.interceptors.request.use(
	(config) => {
		const token = localStorage.getItem('token')
		if (token && config.headers) config.headers.Authorization = 'Bearer ' + token
		config.url = requestBaseURL + config.url
		return config
	},
	(err) => {
		console.log(1, err)
		push.error({
			title: `Error: ${err.response.data.code}`,
			message: err.response.data.msg,
		})
		return Promise.reject(err.response)
	},
)

// 全局 http response 拦截
Axios.interceptors.response.use(
	(res) => {
		const data = res.data
		if (data.code === 0) {
			return data.data
		} else {
			push.error({
				title: `Error: ${data.code}`,
				message: data.msg,
			})
			return Promise.reject(data)
		}
	},
	(err) => {
		console.log(2, err)
		const errorResponse = {
			code: err.response ? err.response.status : 500,
			msg: err.response ? err.response.data.message || '请求错误' : '服务器错误',
			data: '',
		}
		push.error({
			title: `Error: ${errorResponse.code}`,
			message: errorResponse.msg,
		})
		httpErrorHandler(err).then((msg) => {
			push.error({
				title: '请求错误',
				message: msg,
			})
		})
		return Promise.reject(errorResponse)
	},
)

export function Get(url: string, params: any, content = 0) {
	return Axios.get(url, {
		params,
		headers: { 'Content-Type': contentType[content] },
	})
}

export function Post(url: string, data: any, content = 0) {
	return Axios.post(url, data, {
		headers: { 'Content-Type': contentType[content] },
	})
}

export function Del(url: string, data: any, content = 0) {
	return Axios.delete(url, {
		data,
		headers: { 'Content-Type': contentType[content] },
	})
}

export function Put(url: string, data: any, content = 0) {
	return Axios.put(url, data, {
		headers: { 'Content-Type': contentType[content] },
	})
}

export default Axios
